package com.ybg.share.core.shareapi.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ybg.share.core.shareapi.AbstractMarketApi;
import com.ybg.share.core.shareapi.bo.ShareStockDayBO;
import com.ybg.share.core.shareapi.dto.QueryDayDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 易源股票接口
 */
@Service("yiyuanMarketApi")
@Slf4j
public class YiyuanMarketApi extends AbstractMarketApi {
    @Autowired
    YiyuanConfig yiyuanConfig;

    /**
     * 文档地址
     * https://market.aliyun.com/products/56928004/cmapi014124.html?spm=5176.730006-56956004-57000002-cmapi031938.recommend.3.1bb95cbe0VgwIV&innerSource=detailRecommend#sku=yuncode812400000
     *
     * @return
     */
    @Override
    public List<ShareStockDayBO> getDayDate(QueryDayDTO dto) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (yiyuanConfig == null) {
            log.error("没有YiyuanConfig的配置");
            return null;
        }
        try {
            Map<String, Object> params = new LinkedHashMap<>(3);
            params.put("begin", dto.getBegin());
            params.put("code", dto.getCode());
            params.put("end", dto.getEnd());
            String result = HttpUtil.createGet("http://stock.market.alicloudapi.com/sz-sh-stock-history")
                    .header("Authorization", "APPCODE " + yiyuanConfig.getCode())
                    .form(params).execute().body();
            log.info(result);
            JSONObject json = JSON.parseObject(result);
            JSONArray jsonArray = json.getJSONObject("showapi_res_body").getJSONArray("list");
            List<ShareStockDayBO> shareStockDayBOS = jsonArray.toJavaList(ShareStockDayBO.class);
            return shareStockDayBOS;
        } catch (Exception e) {
            log.error("{}", e);

        }


        return null;
    }
}
